
import positionsTpl from '../../views/positions/positions.art'
import positionsListTpl from '../../views/positions/positions-list.art'
import pagination from '../../components/pagination'
import page from '../../databus/page' 

import { addPosition } from './add-position'
import { updataPosition, fillPositionsUpdataTpl } from './updata-position'
import { positionsList as positionsListModel } from '../../models/positions'
// , positionsRemove as positionsRemoveModel
import { remove } from '../common/remove'

let dataList = []

// 观察者
const _substribe = () => {
  $('body').off('changeCurrentPage').on('changeCurrentPage', (event, index) => {
    _list(index)
    page.setCurPage(index)
  })

  $('body').off('addPosition').on('addPosition', (e) => {
    _loadData()
  })
  
  $('body').off('updataPosition').on('updataPosition', (e) => {
    _loadData()
  })
}

const listPosition = (router) => {
  return async (req, res, next) => {
    next()
    res.render(positionsTpl({}))

    // 职位添加
    addPosition()
    // $('#btn-add-position').off('click').on('click', addPosition)
    // 编辑职位
    updataPosition()
    $('#positions-list').off('click').on('click', '.btn-update', function () {
      fillPositionsUpdataTpl($(this).data('id'))
    })

    // 删除指定用户
    // $('#positions-list').on('click', '.btn-remove-position', async function(e){
    //   let res = await positionsRemoveModel($(this).data('id'))
    //   alert(res.data.message)
    //   _loadData()
    // })
    
    _loadData()
    _substribe()
    
    remove({
      $box: $('#positions-list'), 
      url: '/api/positions',
      loadData: _loadData
    })
  }
}

// 渲染数据&分页
function _list(pageNo) {
  if(!dataList || !dataList.length) return
  let pageSize = page.pageSize
  const start = (pageNo - 1) * pageSize
  $('#positions-list').html(positionsListTpl({
    data: dataList.slice(start, start + pageSize)
  }))
}

// 加载用户列表数据
async function _loadData () {
  let res = await positionsListModel()
  console.log(res)
  const list = res.data.list || []
  dataList = list
  // 分页
  pagination(list)
  let currentPage = page.curPage
  _list(currentPage)
}

export default listPosition